package RPC.RPCClient;

import java.io.*;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.Socket;
import java.util.Properties;

public class RPCClient<T> implements InvocationHandler {
    private Class<T> t;
    private static String host;
    private static String port;

    public RPCClient(Class<T> t) {
        this.t = t;
    }

    public T getInstance() {
        return (T) Proxy.newProxyInstance(t.getClassLoader(), new Class[]{t}, this);
    }

    static {
        Properties properties = new Properties();
        try {
            properties.load(RPCClient.class.getClassLoader().getResourceAsStream("RPCconfig.Properties"));
            host = properties.getProperty("host");
            port = properties.getProperty("port");
            System.out.println(host + ":" + port);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Socket socket = new Socket(host, Integer.parseInt(port));
        ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
        oos.writeUTF(t.getSimpleName());
        oos.writeUTF(method.getName());

        oos.writeObject(args);

        //ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
        return "hello"; //ois.readObject();
    }
}
